const arr = [
  { id: 1, name: '总裁办', pid: 0 },
  { id: 11, name: '秘书处', pid: 1 },
  { id: 2, name: 'IT部', pid: 0 }
]

const fn = (arr, val) => {
  const newArr = {}
  arr.forEach(item => {
    if (newArr[item.pid]) {
      newArr[item.pid].push(item)
    } else {
      newArr[item.pid] = [item]
    }
  })
  console.log(newArr)
  arr.forEach(item => {
    const children = newArr[item.id]
    if (children) item.children = children
  })

  return arr.filter(item => item.pid === val)
}
console.log(fn(arr, 0))
// const fn = (arr, val) => {
//   const newArr = []
//   arr.forEach(({ id, pid, ...res }) => {
//     if (pid === val) {
//       const children = fn(arr, id)
//       children.length ? newArr.push({ id, pid, children, ...res }) : newArr.push({ id, pid, ...res })
//     }
//   })
//   return newArr
// }

// console.log(fn(arr, 0))

// const fn1 = (arr, val) => {
//   arr.map(({ id, pid, ...res }) => {
//     if (pid === val) {
//       const children = fn1(arr, id)
//       return children.length ? { id, pid, children, ...res } : { id, pid, ...res }
//     }
//     return []
//   })
// }
// console.log(fn1(arr, 0))
